package me.zhengjie.config.magicapi.interceptor;

import me.zhengjie.utils.SecurityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.modules.db.SQLModule;
import org.ssssssss.magicapi.modules.db.inteceptor.NamedTableInterceptor;
import org.ssssssss.magicapi.modules.db.model.SqlMode;
import org.ssssssss.magicapi.modules.db.table.NamedTable;

import java.util.Date;

/**
 * 表单拦截
 */
@Component
public class CustomNamedTableInterceptor  implements NamedTableInterceptor {


    @Override
    public void preHandle(SqlMode sqlMode, NamedTable namedTable) {

        String userId = null;

        try{
            userId = SecurityUtils.getCurrentUserId().toString();
        }catch (Exception ex){
            //未登录时获取用户信息异常
            userId = "no user";
        }
        if(sqlMode == SqlMode.INSERT) {
            if(!namedTable.getColumns().containsKey("create_by"))
                namedTable.column("create_by", userId);
            if(!namedTable.getColumns().containsKey("create_time"))
                namedTable.column("create_time",new Date());
        }else if(sqlMode == SqlMode.UPDATE){
            if(!namedTable.getColumns().containsKey("update_by"))
                namedTable.column("update_by", userId);
            if(!namedTable.getColumns().containsKey("update_time"))
                namedTable.column("update_time",new Date());
        }
    }
}
